//
//  CSGXHomeSaleController.m
//  CarSalesMS_GCX
//
//  Created by Ssky on 2016/10/25.
//  Copyright © 2016年 Tony. All rights reserved.
//

#import "CSGXHomeSaleController.h"
#import "CSGXHomeSaleCategoryView.h"
#import "CSGXHomeSaleContentView.h"
#import "CSGXHomeSaleCommodityController.h"
#import "CSNavBarView.h"
#import "CSGXBackButton.h"
#import "CSGXHomeSaleCommitPreviewController.h"

#import "TCommodityCategoryDAL.h"
#import "TOrderInfoDAL.h"

#import "TCommodityCategoryModel.h"
#import "TOrderInfoModel.h"


@interface CSGXHomeSaleController () <CSGXCategoryViewActionDelegate, GXScanViewControllerDelegate>

@property (nonatomic, strong) CSGXHomeSaleCommodityController * commodityVc; // vc that owns tvs.

@property(nonatomic,weak) CSGXHomeSaleContentView * vContent; //content view contains tvs.

/// Data of first tv
@property (nonatomic, strong) NSArray<TCommodityCategoryModel *> *commFirstModels;

@property (nonatomic,weak) UILabel *lblSaleCount;
//@property (nonatomic,weak) UILabel *lblSaleMoney;

//orderModel
@property (nonatomic, strong) TOrderInfoModel *orderModel;

@end

@implementation CSGXHomeSaleController
@synthesize saleModelList = _saleModelList;

+ (instancetype)saleVcWithWarehouseNo:(NSString *)warehouseNo {
    CSGXHomeSaleController * saleVc = [[CSGXHomeSaleController alloc] init];
    saleVc.warehouseNo = warehouseNo;
    return saleVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // step 3
    [self loadData_saleVc];
    
    // The observer that scrolls the scrollView  and views detail data for commTv.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedTvCommodityNote:) name:@"tvCommodityCellAction" object:nil];
    
    // receivedDetailViewNewList when the list of detailView has modified.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedDetailViewNewList:) name:@"newListAndOrderModel" object:nil];
    
    self.commodityVc.commFirstModels = self.commFirstModels;
}


- (void)viewWillAppear:(BOOL)animated {
    if (!self.isReceivedHome) {
        [self contentScrollViewScroll];
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    self.isReceivedHome = NO;
    
    self.saleModelList = nil;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - actions
- (void)receivedTvCommodityNote:(NSNotification *)note {
    //    NSLog(@"receivedNote");
    
    [self contentScrollViewScroll];
}

- (void)receivedDetailViewNewList:(NSNotification *)note {
    
    self.saleModelList = note.userInfo[@"newList"];
    self.orderModel = note.userInfo[@"orderModel"];

    [self distributeSaleFooter];
}

- (void)btnCommitAction:(UIBarButtonItem *)btnCommit {
    //
    if (self.saleModelList.count == 0) {
        [CSGXProgressTool showMsgWithStatus:@"您未选择商品，不允许提交！" delay:0.5];
        NSLog(@"Msg：您未选择商品！不允许提交！");
        return;
    }
    
    CSGXHomeSaleCommitPreviewController *previewVc = [[CSGXHomeSaleCommitPreviewController alloc] init];
    previewVc.dataPreviewDict = @{@"orderModel":self.orderModel, @"saleList":self.saleModelList};
    [self.navigationController pushViewController:previewVc animated:YES];
    
}

- (void)btnScanAction:(UIBarButtonItem *)btnScan {
    NSLog(@"btnScanAction");
    
    GXScanViewController * scanVc = [[GXScanViewController alloc] init];
    scanVc.scanDelegate = self;
    [self presentViewController:scanVc animated:YES completion:nil];
}

- (void)btnSearchAction:(UIBarButtonItem *)btnSearch {
    
}

#pragma mark - methods

- (void)contentScrollViewScroll {
    //
    [self.vContent setContentOffset:CGPointMake(2 * self.view.gx_Width / 3, 0) animated:YES];
}

- (void)distributeSaleFooter {
//    NSDictionary *dict = note.userInfo;
    //%@条(大%@/中%@/小%@) ￥%.2f
    NSArray *countArr = [self.orderModel.orCount componentsSeparatedByString:@","];
    NSString *countLblStr = [NSString stringWithFormat:@"%@条(大%@/中%@/小%@) ￥%.2f", @(self.saleModelList.count), countArr[0], countArr[1], countArr[2], self.orderModel.orTotalMoney];
    
    self.lblSaleCount.text = countLblStr;
}



#pragma mark - delegates
#pragma mark --CSGXCategoryViewActionDelegate
- (void)gxCategoryView:(CSGXHomeSaleCategoryView *)categoryView withSelectedIndex:(NSInteger)selectedIdnex {
    //    NSLog(@"CSGXHomeSaleCategoryViewAction:%zd", selectedIdnex);
    
    self.commodityVc.dataIndex = selectedIdnex;
    
    [self.vContent setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)gxScanVc:(GXScanViewController *)scanVc backObject:(NSString *)backObject backObjectType:(BackObjectType)backObjectType {
    //
    if (backObjectType == kObjectTypeDefault) {
        NSLog(@"没扫到任何鸟……");
        return;
    }
    
    if (backObjectType == kObjectTypeString) { //字符串
        [self contentScrollViewScroll];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.commodityVc.commodityNo = backObject;
        });

    }else {
        UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"商品扫描" message:@"您扫描的是一个飞往火星的网址，请重试！" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 取消
        }];
        [alertVc addAction:actionCancel];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:alertVc animated:YES completion:nil];
        });
    }
    
}


#pragma mark - setupUI
- (void)setupNavBar {
    UIBarButtonItem * rightCommit = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(btnCommitAction:)];
    UIBarButtonItem * rightScan = [[UIBarButtonItem alloc] initWithTitle:@"扫描" style:UIBarButtonItemStylePlain target:self action:@selector(btnScanAction:)];
    UIBarButtonItem * rightSearch = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(btnSearchAction:)];
    
    self.navigationItem.rightBarButtonItems = @[rightCommit, rightScan, rightSearch];
}

- (void)setupUI {
    // navBar
    [self setupNavBar];
    
    // categoryView
    CSGXHomeSaleCategoryView * vCategory = [CSGXHomeSaleCategoryView gxCategoryViewWithDelegate:self page:0];
    [self.view addSubview:vCategory];
    
    vCategory.lineColor = kColorButton;
    vCategory.isLine = YES;
    
    vCategory.segments = @[@"销售", @"处理", @"还货", @"换货", @"退货"];
    
    [vCategory mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.leading.trailing.equalTo(self.view);
        make.height.mas_offset(kHeightCategory);
    }];
    [self.view layoutIfNeeded];
    
    // contentView
    CSGXHomeSaleContentView * vcontent = [[CSGXHomeSaleContentView alloc] init];
    [self.view addSubview:vcontent];
    self.vContent = vcontent;
    
    [vcontent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vCategory.mas_bottom).mas_offset(0);
        make.leading.trailing.equalTo(self.view);
    }];
#pragma mark add child viewController
    // add child viewController
    CSGXHomeSaleCommodityController * commodityVc = [CSGXHomeSaleCommodityController commodityVcWithWarehouseNo:self.warehouseNo];
    self.commodityVc = commodityVc;
    
    // step 1
    [self gx_addChildController:commodityVc intoView:vcontent];
    // 布局
    [commodityVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.trailing.equalTo(vcontent);
    }];
    
    //vFooter
    UIView *vFooter = [[UIView alloc] init];
    [self.view addSubview:vFooter];
    
    vFooter.backgroundColor = kColorBar;
    
    [vFooter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(vcontent.mas_bottom);
        make.leading.bottom.trailing.equalTo(self.view);
        make.height.mas_offset(30);
    }];
    
    UILabel *lblSaleCount = [UILabel gx_labelWithText:@"0条（0/0）￥0.00" fontSize:12 color:[UIColor whiteColor]];
    [vFooter addSubview:lblSaleCount];
    
    [lblSaleCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(vFooter);
        make.leading.equalTo(vFooter).offset(5);
    }];
    
    //
    self.lblSaleCount = lblSaleCount;
//    self.lblSaleMoney = lblSaleMoney;
}



#pragma mark - laodData
- (void)loadData_saleVc {
    self.commFirstModels = [TCommodityCategoryDAL loadCoCategoryModelFirstWithWarehouseNo:self.warehouseNo]; //Only have caFirstTypes.
}


#pragma mark - setter & getter

- (void)setSaleModelList:(NSArray<TSaleInfoModel *> *)saleModelList {
    _saleModelList = saleModelList;
    
    if (!saleModelList) {
        return;
    }
    
    self.commodityVc.saleModelList = saleModelList;
    
}




@end
